package com.nexgo.payment.action.online.upload;

import com.nexgo.payment.App;
import com.nexgo.payment.R;
import com.nexgo.payment.constrant.PreferencesConstants;
import com.nexgo.payment.constrant.TransType;
import com.nexgo.payment.databases.DataSource;
import com.nexgo.payment.databases.Signature;
import com.nexgo.payment.databases.TransRecord;
import com.nexgo.payment.entity.MessageData;
import com.nexgo.payment.entity.TransData;
import com.nexgo.payment.util.StringUtils;
import com.nexgo.payment.util.TransUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 单次上送电子签名父级
 * <p>
 * Created by xiaox on 2017/9/14.
 */
abstract class AbsUploadEs extends Upload {
    private final Logger log;
    private OnUploadListener mListener;
    private final List<Signature> mSignatures;
    private TransRecord mTransRecord;
    private Signature mSignature;
    private int mIdx = 0;
    private boolean mForceBreak;

    AbsUploadEs(DataSource repository) {
        super(repository);
        log = LoggerFactory.getLogger(getClass().getSimpleName());
        mSignatures = getUploadSignatures();
    }

    abstract List<Signature> getUploadSignatures();

    @Override
    TransData buildTransData() {
        TransData transData = new TransData();
        transData.setTransType(TransType.UPLOAD_ES);
        transData.setOrgTraceNum(mTransRecord.getTraceNum());
        return transData;
    }

    @Override
    public void sendTrans(OnUploadListener listener) {
        mListener = listener;
        sendOrComplete();
    }

    @Override
    void onTransResponseCheckError(String responseCode) {
        if (TransUtils.isNeedReLogin(responseCode)) {
            mRepository.setParamValue(PreferencesConstants.IS_NEED_LOGIN, "1");
            mRepository.syncParamValue();
            //强制退出
            mForceBreak = true;
        } else if (TransUtils.isRepeatedTrans(responseCode)) {
            //重复上送
            updateSignatureUploadState(true, true);
        } else {
            //被拒
            updateSignatureUploadState(true, false);
        }
    }

    @Override
    void onTransResponse(MessageData messageData) {
        updateSignatureUploadState(true, true);
    }

    @Override
    void onTransTimeout() {
        updateSignatureUploadState(true, false);
        sendOrComplete();
    }

    @Override
    void onTransFailed() {
        mListener.onUploadFailed();
    }

    @Override
    void onTransComplete() {
        if (mForceBreak) {
            onTransFailed();
        } else {
            sendOrComplete();
        }
    }

    @Override
    public boolean isOverMaxReUploadTimes() {
        return sUploadCounter >= getMaxReUploadTimes();
    }

    private int getMaxReUploadTimes() {
        return Integer.parseInt(StringUtils.firstNonEmpty(mRepository.getParamValue(PreferencesConstants.SIGNATURE_UPLOAD_TIMES), "3"));
    }

    private void sendOrComplete() {
        if (hasNext()) {
            log.debug("存在需要上送的电子签名");
            mListener.onShowTip(App.sContext.getString(R.string.upload_es));
            send();
        } else {
            log.debug("电子签名上送结束");
            mListener.onUploadComplete();
        }
    }

    protected boolean hasNext() {
        if (mSignatures == null) {
            return false;
        }
        for (int i = mIdx; i < mSignatures.size(); i++) {
            Signature signature = mSignatures.get(i);
            mIdx = i + 1;
            mSignature = signature;
            mTransRecord = mRepository.queryTransRecord(signature.getTraceNum());
            if (mTransRecord == null) {
                continue;
            }
            log.debug("当笔上送状态，已上送{}，上送成功{}", mSignature.getIsEverUpload(), mSignature.getIsUploadSuccessful());
            return true;
        }
        return false;
    }

    void updateSignatureUploadState(boolean isUploaded, boolean isUploadSuccessful) {
        log.debug("更新上送状态，已上送{}，上送成功{}", isUploaded, isUploadSuccessful);
        mSignature.setIsEverUpload(isUploaded);
        mSignature.setIsUploadSuccessful(isUploadSuccessful);
        mRepository.updateSignature(mSignature);
    }
}
